import React, { useState } from "react";
import useSWR from "swr";
import { fetcher } from "../utils";
import { useNavigate } from "react-router-dom";

function GradeEntry() {
    const navigate = useNavigate();
    const [selectedClass, setSelectedClass] = useState("");
    const [grades, setGrades] = useState({});
    const [isBusy, setBusy] = useState(false);
    const [actionError, setActionError] = useState(null);

    // 拉取班次和学生-课程信息
    const { data: classList } = useSWR("/api/class/list", fetcher);
    // 选中班次后，拉取该班次下所有学生和课程
    const { data: electiveList } = useSWR(selectedClass ? `/api/elective/list?class_sn=${selectedClass}` : null, fetcher);

    // 处理成绩输入
    const handleGradeChange = (stu_sn, value) => {
        setGrades(prev => ({ ...prev, [stu_sn]: value }));
    };

    const handleSave = async () => {
        if (!selectedClass) {
            setActionError("请选择班次");
            return;
        }
        setBusy(true);
        setActionError(null);
        try {
            let response = await fetch("/api/grade/batch", {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify({ class_sn: parseInt(selectedClass), grades }),
            });
            if (!response.ok) {
                let errorText = await response.text();
                setActionError(errorText);
                return;
            }
            navigate("/grade/list");
        } finally {
            setBusy(false);
        }
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>按班次录入成绩</h3>
            </div>
            <div className="paper-body">
                <div className="field">
                    <label>班次：</label>
                    <select value={selectedClass} onChange={e => setSelectedClass(e.target.value)}>
                        <option value="">请选择班次</option>
                        {classList && classList.map(cls => (
                            <option key={cls.sn} value={cls.sn}>{cls.name}</option>
                        ))}
                    </select>
                </div>
                {selectedClass && electiveList && (
                    <table className="table">
                        <thead>
                            <tr>
                                <th>学生姓名</th>
                                <th>成绩</th>
                            </tr>
                        </thead>
                        <tbody>
                            {electiveList.map(item => (
                                <tr key={item.stu_sn}>
                                    <td>{item.stu_name}</td>
                                    <td>
                                        <input
                                            type="number"
                                            value={grades[item.stu_sn] || ""}
                                            onChange={e => handleGradeChange(item.stu_sn, e.target.value)}
                                            style={{ width: 80 }}
                                        />
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                )}
                {actionError && <div className="error">{actionError}</div>}
            </div>
            <div className="paper-footer">
                <button className="btn" onClick={handleSave} disabled={isBusy}>保存</button>
                <button className="btn" onClick={() => navigate("/grade/list")}>返回</button>
            </div>
        </div>
    );
}

export default GradeEntry; 